package com.xnf.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xnf.model.common.dtos.ResponseResult;
import com.xnf.model.common.enums.AppHttpCodeEnum;
import com.xnf.model.wemeida.dtos.WmUserDto;
import com.xnf.model.wemeida.pojos.WmUser;
import com.xnf.utils.common.AppJwtUtil;
import com.xnf.wemedia.mapper.WmUserMapper;
import com.xnf.wemedia.service.WmUserService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xnf on 2022/3/30.
 */
@Service
@Log4j2
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper,WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.检查参数
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码错误");
        }
        //2.查询数据库中的用户信息
        WmUser wmUser = baseMapper.selectOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (wmUser != null){
            String psw = dto.getPassword() + wmUser.getSalt();
            psw = DigestUtils.md5Hex(psw.getBytes());
            if (psw.equals(wmUser.getPassword())){
                //4.返回数据jwt
                Map<String,Object> map = new HashMap<>();
                map.put("token",AppJwtUtil.getToken(wmUser.getId().longValue()));
                wmUser.setPassword("");
                wmUser.setSalt("");
                map.put("user",wmUser);
                return ResponseResult.okResult(map);
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
    }
}
